<template>
  <div class="login">
    <div class="loginword">登录</div>
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="username"
          name="手机号"
          label="手机号"
          placeholder="请输入手机号"
          :rules="[{ required: true, message: '请填写手机号', pattern }]"
        />
        <van-field
          v-model="password"
          type="password"
          name="密码"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          登录
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { reactive, toRefs } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";

export default {
  setup() {
    //数据
    let states = reactive({
      username: "",
      password: "",
      //校验手机号
      pattern: /^1[3|4|5|7|8][0-9]{9}$/,
    });

    //vuex
    let { dispatch, commit } = useStore();
    //路由
    let router = useRouter();

    async function onSubmit(values) {
      let data = await dispatch("user/getUserLogin", {
        username: states.username,
        password: states.password,
      });
      if (data.code == 200) {
        commit("user/CHNAGEISLOGIN", true);
        router.push("/userCenter");
      } else {
        console.log(data.message);
      }
    }

    return {
      ...toRefs(states),
      onSubmit,
    };
  },
};
</script>

<style lang="less" scoped>
.login {
  width: 100%;
  height: 12rem;
  background-color: rgb(233, 239, 239);
  display: flex;
  flex-direction: column;
  align-items: center;
  .loginword {
    margin: 2rem 0 1rem;
    font-size: 0.8rem;
    color: rgb(108, 54, 54);
  }
}
</style>